package com.springboot.springbootmybatisannotation.config;

import com.springboot.springbootmybatisannotation.intercepter.ControllerLevelAopIntercepter;
import com.springboot.springbootmybatisannotation.tenant.MybatisPlusInterceptor;
import com.springboot.springbootmybatisannotation.tenant.TenantLineHandler;
import com.springboot.springbootmybatisannotation.tenant.TenantLineInnerInterceptor;
import com.springboot.springbootmybatisannotation.utils.ObjUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author miemie
 * @since 2018-08-10
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                String cityId = ControllerLevelAopIntercepter.currentStaff();
                if (ObjUtils.isNotEmpty(cityId)) {
                    return new LongValue(Long.parseLong(cityId));
                }
                return new LongValue(0);
            }

            // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
            @Override
            public boolean ignoreTable(String tableName) {
                return !"user".equalsIgnoreCase(tableName);
            }
        }));
        // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
        // 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false
//        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }


}
